const labelService = require("../service/label.service");
/**
 * 校验labels是否存在
 */
const verifyLabelExists = async (ctx, next) => {
  // 1.获取客户端传递过来所有的labels
  const { labels } = ctx.request.body

  // 2.判断所有的labels中的name是否存在于label表中
  let newLabels = []
  for(let name of labels){
    const reslut = await labelService.queryLabelByName(name)
    let labelObj = {name}
    if (reslut) { // 获取name对应的label的id
      labelObj.id = reslut.id // => {name: '篮球', id: 1}
    }else{ // 插入name，并且获取插入之后的id
      const insertReslut = await labelService.create(name)
      labelObj.id = insertReslut.insertId
    }
    newLabels.push(labelObj)
  }

  // 3.将所有的labels都变为[{name: '篮球', id: 1},{name: '篮球', id: 1}]
  ctx.labels = newLabels
  await next()
}

module.exports = {
    verifyLabelExists
}